﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using Pg.BioMedics.SDR.Diagnostics;

namespace Pg.BioMedics.SDR.Web.Modules
{
    /// <summary>
    /// Http module supporting performance / diagnostic functionaloty of the 
    /// SDR system
    /// </summary>
    public class DiagnosticModule : IHttpModule
    {
        #region Event handlers

        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            WebPerformanceCounters.Instance.AvgRequestSize.Set(app.Request.TotalBytes);
            WebPerformanceCounters.Instance.NumberOfRequests.Add(1);
            WebPerformanceCounters.Instance.AvgResponseTime.Start(app.Request.Url.ToString());
        }

        private void OnEndRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            //WebPerformanceCounters.Instance.AvgResponseSize.Set(app.Response.s);
            WebPerformanceCounters.Instance.NumberOfRequests.Sub(1);
            WebPerformanceCounters.Instance.AvgResponseTime.Stop(app.Request.Url.ToString());
        } 

        #endregion

        #region IHttpModule Members

        /// <summary>
        /// Provides hendler bindings to the current instance of the HttpApplication
        /// </summary>
        /// <param name="context">Application context</param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
            context.EndRequest += new EventHandler(OnEndRequest);
        }               

        public void Dispose()
        {            
        }

        #endregion
    }
}
